const {
    app,
    BrowserWindow,
    ipcMain,
    Menu,
    Tray,
    nativeImage,
    global_shortcut
} = require('electron');
const path = require('path');
const wd = require('./js/window.js');
const {
    autoUpdater
} = require('electron-updater');

const {
    allconfig
} = require('./js/config');

var mainwindow = null;
process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true';
let tray; //系统托盘


function createWindow() {
    mainwindow = new BrowserWindow({
        icon: path.join(__dirname, './img/logo/favicon48.ico'),
        width: 1200,
        height: 750,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),
            nodeIntegration: true,
            contextIsolation: false,
            enableRemoteModule: true,
            webviewTag: true,
        }
    })
    mainwindow.loadFile('login.html');
    if (allconfig.debug) {
        mainwindow.webContents.openDevTools();
    }


    mainwindow.on('close', function (e) {
        e.preventDefault();
        wd.minWindow(mainwindow);
    });

    //定义为全局
    global.mainwindow = mainwindow;
}

// in main process, outside of app.on:
ipcMain.on('loadpage', (event, arg) => {
    // console.log(arg);
    mainwindow.loadFile(arg);
});



app.whenReady().then(() => {
    //去除菜单栏
    // Menu.setApplicationMenu(null);

    //启动窗口
    createWindow();


    //系统托盘
    const icon = nativeImage.createFromPath(path.join(__dirname, './img/logo/favicon48.ico'));
    tray = new Tray(icon);


    const contextMenu = Menu.buildFromTemplate([{
            label: '打开主面板',
            type: 'normal',
            click: function (menuItem, browserWindow, event) {
                if (!mainwindow.isVisible()) {
                    mainwindow.show();
                }
            }
        },
        {
            label: '退出',
            type: 'normal',
            click: function (menuItem, browserWindow, event) {
                app.exit();
            }
        }
    ])

    tray.setContextMenu(contextMenu);
    tray.setToolTip('新点工具箱');
    tray.setTitle('工具箱标题');
    tray.on('double-click', (event, options) => {
        wd.showWindow(mainwindow);
    });



    ipcMain.on('opendialog', (event, options) => {

        let newwin = new BrowserWindow({
            icon: './img/logo/favicon48.ico',
            // title: options.title ? options.title : '新窗口',
            width: options.width ? options.width : mainwindow.innerWidth * 0.8,
            height: options.height ? options.height : mainwindow.innerHeight * 0.8,
            modal: true,
            parent: mainwindow,
            webPreferences: {
                devTools: allconfig.debug,
                nodeIntegration: true, //启动node集成
                nodeIntegrationInWorker: true,
                nodeintegrationinsubframes: true,
                contextIsolation: false,
                enableRemoteModule: true,
                webviewTag: true
            },
        })

        let url = options.url.indexOf('http') == 0 ? options.url : path.join('file:', __dirname, options.url);
        newwin.loadURL(url); //new.html是新开窗口的渲染进程
        newwin.on('closed', () => {
            newwin = null
        });
        if (allconfig.debug) {
            newwin.webContents.openDevTools();
        }
    });


    //检查更新
    updateHandle();



    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) {
            createWindow();
        }
    })

})


// 检测更新，在你想要检查更新的时候执行，renderer事件触发后的操作自行编写
function updateHandle() {
    let message = {
        error: '检查更新出错',
        checking: '正在检查更新……',
        updateAva: '检测到新版本，正在下载……',
        updateNotAva: '现在使用的就是最新版本，不用更新',
    };

    autoUpdater.setFeedURL(allconfig.updateurl);
    autoUpdater.on('error', function (error) {
        sendUpdateMessage(message.error)
    });
    autoUpdater.on('checking-for-update', function () {
        sendUpdateMessage(message.checking)
    });
    autoUpdater.on('update-available', function (info) {
        sendUpdateMessage(message.updateAva)
    });
    autoUpdater.on('update-not-available', function (info) {
        sendUpdateMessage(message.updateNotAva)
    });

    // 更新下载进度事件
    autoUpdater.on('download-progress', function (progressObj) {
        mainwindow.webContents.send('downloadProgress', progressObj)
    })
    autoUpdater.on('update-downloaded', function (event, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) {

        sendUpdateMessage('isUpdateNow'), 2000

        ipcMain.on('updateNow', (e, arg) => {
            console.log(arguments);
            console.log("开始更新");
            //some code here to handle event
            autoUpdater.quitAndInstall();
        });


    });

    ipcMain.on("checkForUpdate", (event, options) => {
        //执行自动更新检查
        autoUpdater.checkForUpdates();
    });


}

// 通过main进程发送事件给renderer进程，提示更新信息
function sendUpdateMessage(text) {
    mainwindow.webContents.send('message', text)
}

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit()
    }
    global_shortcut.unregisterAll();
})
